<template>
  <a-form ref="ruleForm" :model="formData" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
    <a-form-item label="旧密码" name="old_pwd" v-show="oldShow">
      <a-input-password v-model:value="formData.old_pwd" :placeholder="rules.old_pwd[0].message" />
    </a-form-item>
    <a-form-item label="新密码" name="new_pwd">
      <a-input-password v-model:value="formData.new_pwd" :placeholder="rules.new_pwd[0].message" />
    </a-form-item>
    <a-form-item label="确认密码" name="reset_new_pwd">
      <a-input-password v-model:value="formData.reset_new_pwd" :placeholder="rules.reset_new_pwd[0].message" />
    </a-form-item>
  </a-form>
</template>

<script>
import { oldPwdUpdateNewPwd } from '../../api/index.js';
import { getRememberedInfo, isStrongPasswd, setRememberedInfo } from '../../views/login/utils.js';

export default {
  name: 'UpdatePassword',
  props: {
    oldPassword: { type: String, default: '' },
  },
  data() {
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        if (!isStrongPasswd(value)) {
          callback(new Error('密码必须由字母+数字+特殊字符组成'));
        } else if (value == this.formData.old_pwd) {
          callback(new Error('新密码与旧密码一致'));
        } else {
          callback();
        }
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'));
      } else if (value !== this.formData.new_pwd) {
        callback(new Error('两次密码不一致'));
      } else {
        callback();
      }
    };
    return {
      oldShow: true,
      formData: {},
      rules: {
        old_pwd: [{ required: true, message: '请输入旧密码' }],
        new_pwd: [
          { required: true, message: '请输入新密码' },
          { validator: validatePass, trigger: 'blur' },
        ],
        reset_new_pwd: [
          { required: true, message: '请再次输入新密码' },
          { validator: validatePass2, trigger: 'blur' },
        ],
      },
    };
  },
  mounted() {
    if (this.oldPassword) {
      this.formData.old_pwd = this.oldPassword;
      this.oldShow = false;
    }
  },
  methods: {
    async onOk() {
      const valid = await this.$refs.ruleForm.validate();
      if (!valid) return false;
      const params = { old_pwd: this.formData.old_pwd, new_pwd: this.formData.new_pwd };
      const res = await oldPwdUpdateNewPwd(params);
      if (res && res.code == 200) {
        this.$message.success(res.msg);
        let data = getRememberedInfo();
        setRememberedInfo(true, Object.assign({}, data, { password: this.formData.new_pwd }));
        return true;
      } else {
        this.$message.error(res.msg);
        return false;
      }
    },
  },
};
</script>

<style scoped></style>
